/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cuong.bean;

import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Admin Windows 8
 */
@ManagedBean
@SessionScoped
public class LanguageBean {

    /**
     * Creates a new instance of LanguageBean
     */
    public LanguageBean() {
    }
    private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }
    private static final long serialVersionUID = 1L;
    private String localeCode;
    private static Map<String, Object> countries;

    static {
        countries = new LinkedHashMap<String, Object>();
        countries.put("English", Locale.ENGLISH); //label, value
        countries.put("Vietnam", new Locale("vi", "VN"));
    }

    public String getLocaleCode() {
        return localeCode;
    }

    public void setLocaleCode(String localeCode) {
        this.localeCode = localeCode;
    }

    public static Map<String, Object> getCountriesInMap() {
        return countries;
    }

    //value change event listener
    public void countryLocaleCodeChanged(String value) {

        String newLocaleValue = value;

        //loop country map to compare the locale code
        for (Map.Entry<String, Object> entry : countries.entrySet()) {

            if (entry.getValue().toString().equals(newLocaleValue)) {

                FacesContext.getCurrentInstance()
                        .getViewRoot().setLocale((Locale) entry.getValue());
                locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();

            }
        }
//        FacesContext fc = FacesContext.getCurrentInstance();
//        HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
//        String s = getFullURL(request);
//        return s + "?faces-redirect=true";
    }

    public static String getFullURL(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String queryString = request.getQueryString();

        if (queryString == null) {
            return requestURL.toString();
        } else {
            return requestURL.append('?').append(queryString).toString();
        }
    }
}
